import urlConfig from "./urlConfig.js"; // 引入接口地址配置
import {
	addRequestTask,
	removeCurrentPageCurrentRequestTask,
} from "./requestCancel";
import store from '@/store'
let that = this
// 封装请求类
class Request {
	constructor(config = {}) {
		// 常用contentType
		this.contentType = {
			0: "application/json;charset=UTF-8",
			1: "application/x-www-form-urlencoded;charset=UTF-8",
			2: "multipart/form-data",
		};
		// 默认配置
		this.defaultConfig = Object.assign({
			baseURL: urlConfig.baseURL, // 接口根地址
			contentTypeIndex: 0, // 默认contentType索引
			url: "", // 请求地址
			method: "POST", // 默认请求方法
			data: {}, // 默认data的参数
			mask: false, // 请求提示弹框是否开启遮罩
			showMessage: true, // 这个接口是否需要显示错误消息提示
			timeout: 20000, // 默认接口超时时间
			extra: "", // 请求的额外参数，用于区分不同请求用
			isAddRequestTask: true, // 是否将当前请求，添加到请求任务集合
			isRemoveCurrentPageCurrentRequestTask: false, // 是否取消当前路由下的指定请求
		},
			config
		);
		this.requestTimer = null; // 定时器
	}

	// 动态处理接口url里面的/
	setRequestUrl(url) {
		let {
			baseURL
		} = this.defaultConfig;
		// 如果是完整地址了，直接返回url
		if (/^http(s)?:\/\//.test(url)) {
			return url;
		}
		// 如果baseURL是以/结尾的，就将结尾的/替换成空字符串
		if (/\/$/.test(baseURL)) {
			baseURL = baseURL.replace(/\/$/, "");
		}
		// 如果url不是以/开头的就将url前面拼接一个/
		if (!/^\//.test(url)) {
			url = "/" + url;
		}
		return baseURL + url;
	}

	// 请求弹框
	requestToast(title, mask) {
		const {
			requestTimer
		} = this;
		// 调用之前清除定时器
		requestTimer && clearTimeout(requestTimer);
		this.requestTimer = null;
		// 因为showToast和showLoading底层是一个东西，所以做下延时
		this.requestTimer = setTimeout(() => {
			uni.showToast({
				title: title || "",
				icon: "none",
				duration: 1500,
				// #ifndef MP-TOUTIAO
				mask: mask !== false,
				// #endif
			});
		}, 10);
	}

	// 请求函数
	request(config = {}) {
		const {
			contentType,
			defaultConfig
		} = this;
		// 将传递的参数和默认参数合并
		const currentConfig = Object.assign({}, defaultConfig, config);
		const requestUrl = this.setRequestUrl(currentConfig.url);
		return new Promise((resolve, reject) => {
			// 判断是否取消当前路由下的指定请求
			currentConfig.isRemoveCurrentPageCurrentRequestTask &&
				removeCurrentPageCurrentRequestTask(currentConfig);
			const requestTask = uni.request({
				url: requestUrl,
				// 这里防止有时候传小写的get post delete put等，都转换成大写
				method: currentConfig.method.toUpperCase(),
				timeout: currentConfig.timeout,
				header: {
					"Content-Type": contentType[currentConfig.contentTypeIndex],
					// userAccessToken: uni.getStorageSync("App-Token") || "",
					"Authorization": 'Bearer ' + uni.getStorageSync("App-Token") || ""
				},
				data: currentConfig.data || defaultConfig.data,
				success: (res) => {
					const resData = res.data || {};
					const statusCode = res.statusCode;
					// 处理statusCode为200、正常情况
					if (statusCode === 200) {
						switch (resData.code) {
							case 200:
							case "200":
								resolve(resData);
								break;
							case 501:
							case "501":
								// #ifndef APP-PLUS
								console.log("无权限接口信息", {
									baseURL: currentConfig.baseURL,
									url: currentConfig.url,
									method: currentConfig.method,
									data: currentConfig.data || defaultConfig.data,
									statusCode,
									response: resData,
								});
								// #endif
								// #ifdef APP-PLUS
								console.log(
									"无权限接口信息",
									JSON.stringify({
										baseURL: currentConfig.baseURL,
										url: currentConfig.url,
										method: currentConfig.method,
										data: currentConfig.data || defaultConfig.data,
										statusCode,
										response: resData,
									})
								);
								// #endif
								currentConfig.showMessage &&
									this.requestToast(
										resData.msg || "登录信息已失效，请重新登录",
										currentConfig.mask
									);
								reject(resData);
								// 退出登录
								store.dispatch("chronic/resetStore").finally(() => {
									// uni.setStorageSync("nav_to_index_index", 1)
									// uni.reLaunch({
									// 	url: "/pages/index/index"
									// })
									// uni.reLaunch({
									// 	url: "/chronicDisease/pages/login/loginEmpty",
									// });
								});
								break;
							default:
								// #ifndef APP-PLUS
								console.log("异常接口信息", {
									baseURL: currentConfig.baseURL,
									url: currentConfig.url,
									method: currentConfig.method,
									data: currentConfig.data || defaultConfig.data,
									statusCode,
									response: resData,
								});
								// #endif
								// #ifdef APP-PLUS
								console.log(
									"异常接口信息",
									JSON.stringify({
										baseURL: currentConfig.baseURL,
										url: currentConfig.url,
										method: currentConfig.method,
										data: currentConfig.data || defaultConfig.data,
										statusCode,
										response: resData,
									})
								);
								// #endif
								currentConfig.showMessage &&
									this.requestToast(
										resData.msg || "服务器未知异常",
										currentConfig.mask
									);
								reject(resData);
								break;
						}
					} else {
						// 处理statusCode非200、异常情况
						switch (resData.code) {
							case 501:
							case "501":
								// #ifndef APP-PLUS
								console.log("无权限接口信息", {
									baseURL: currentConfig.baseURL,
									url: currentConfig.url,
									method: currentConfig.method,
									data: currentConfig.data || defaultConfig.data,
									statusCode,
									response: resData,
								});
								// #endif
								// #ifdef APP-PLUS
								console.log(
									"无权限接口信息",
									JSON.stringify({
										baseURL: currentConfig.baseURL,
										url: currentConfig.url,
										method: currentConfig.method,
										data: currentConfig.data || defaultConfig.data,
										statusCode,
										response: resData,
									})
								);
								// #endif
								currentConfig.showMessage &&
									this.requestToast(
										resData.msg || "登录信息已失效，请重新登录",
										currentConfig.mask
									);
								reject(resData);
								// 退出登录
								store.dispatch("chronic/resetStore").then(() => {
									// uni.reLaunch({
									// 	url: "/chronicpages/pages/login/loginEmpty",
									// });
									uni.setStorageSync("nav_to_index_index", 1)
									uni.reLaunch({
										url: "/pages/index/index"
									})
								});
								break;
							default:
								// #ifndef APP-PLUS
								console.log("异常接口信息", {
									baseURL: currentConfig.baseURL,
									url: currentConfig.url,
									method: currentConfig.method,
									data: currentConfig.data || defaultConfig.data,
									statusCode,
									response: resData,
								});
								// #endif
								// #ifdef APP-PLUS
								console.log(
									"异常接口信息",
									JSON.stringify({
										baseURL: currentConfig.baseURL,
										url: currentConfig.url,
										method: currentConfig.method,
										data: currentConfig.data || defaultConfig.data,
										statusCode,
										response: resData,
									})
								);
								// #endif
								currentConfig.showMessage &&
									this.requestToast(
										resData.msg || "服务器未知异常",
										currentConfig.mask
									);
								reject(resData);
								break;
						}
					}
				},
				fail: (err) => {
					const {
						errMsg = ""
					} = err;
					// 请求超时
					if (errMsg.includes("timeout")) {
						currentConfig.showMessage &&
							this.requestToast(
								"请求超时，网络或服务器异常",
								currentConfig.mask
							);
						console.log("请求超时，网络或服务器异常", {
							baseURL: currentConfig.baseURL,
							url: currentConfig.url,
							method: currentConfig.method,
							data: currentConfig.data || defaultConfig.data,
							errMsg,
						});
					} else if (errMsg.includes("abort")) {
						console.log("请求已取消", {
							baseURL: currentConfig.baseURL,
							url: currentConfig.url,
							method: currentConfig.method,
							data: currentConfig.data || defaultConfig.data,
							errMsg,
						});
					} else {
						// 请求失败
						currentConfig.showMessage &&
							this.requestToast(
								"请求失败，网络或服务器异常",
								currentConfig.mask
							);
						console.log("请求失败，网络或服务器异常", {
							baseURL: currentConfig.baseURL,
							url: currentConfig.url,
							method: currentConfig.method,
							data: currentConfig.data || defaultConfig.data,
							errMsg,
						});
					}
					reject(err);
				},
			});
			// 判断是否添加请求任务
			currentConfig.isAddRequestTask &&
				addRequestTask({
					baseURL: currentConfig.baseURL,
					url: currentConfig.url,
					method: currentConfig.method,
					data: currentConfig.data || defaultConfig.data,
					extra: currentConfig.extra,
				},
					requestTask
				);
		});
	}

	// get请求
	get(config = {}) {
		return this.request({
			method: "GET",
			...config,
		});
	}

	// post请求
	post(config = {}) {
		return this.request({
			method: "POST",
			...config,
		});
	}

	// put请求
	put(config = {}) {
		return this.request({
			method: "PUT",
			...config,
		});
	}

	// delete请求
	delete(config = {}) {
		return this.request({
			method: "DELETE",
			...config,
		});
	}
}

export default Request;